function $(val) {
    const el = document.querySelectorAll(val);
    if (el.length === 1) {
        return el[0];
    } else {
        return el;
    }

}

function bindEvent() {
    const gender_selector = $('div.gender');
    gender_selector.addEventListener('click', (e) => {
        const tar = e.target;
        const type = tar.getAttribute('data-gender');
        if (type === 'male') {
            gender_selector.setAttribute('data-selected-gender', 'male');
        } else if (type === 'female') {
            gender_selector.setAttribute('data-selected-gender', 'female');
        } else {
            return;
        }
        gender_selector.querySelectorAll('.select').forEach((el) => el.classList.remove('selected'));
        tar.classList.toggle('selected');
    })
}

function getFormValues() {
    return {
        name: $('input[name="name"]').value.trim(),
        email: $('input[name="email"]').value.trim(),
        gender: $('div.gender').getAttribute('data-selected-gender'),
        password: $('input[name="password"]').value.trim(),
        repassword: $('input[name="repassword"]').value.trim(),
        date: $('input[name="date"]').value.trim()
    }
}

function formValidator(formData, dataRules) {
    const errors = {};
    Object.entries(dataRules).forEach(([name, rules]) => {
        rules.forEach((rule) => {
            const success = rule.validator(formData[name]);
            if (!success && !errors[name]) {
                //errors已经有这个属性的错误信息了就不替换，优先采用前面优先级高的
                errors[name] = rule.message;
            }
        });
    })
    if (formData.password !== formData.repassword) {
        errors['repassword'] = '两次密码必须一致';
    }
    return errors;
}

function handleMessage(errors) {

    clearErrors();
    Object.entries(errors).forEach(([key, value]) => {
        const name = key, message = value;
        console.log(name, message);
        const inp = $(`input[name="${name}"]`);
        const div = name === 'gender' ? $('.gender') : inp.parentNode;
        console.log(div);
        div.classList.add('error');

        div.insertAdjacentHTML('afterend', `<div class="error-message">${message}</div>`);
    });

}

function clearErrors() {
    const error_messages = $('.error-message');

    error_messages.length ? error_messages.forEach((el) => el.remove()) : (error_messages.length === 0 || error_messages.remove());

    $('div.item').forEach((el) => el.classList.remove('error'));
}


function handleSumbit(e) {
    e.preventDefault();
    const formData = getFormValues();
    const errors = formValidator(formData, rules);
    if (Object.keys(errors).length) {
        handleMessage(errors);
    } else {
        clearErrors();
        setTimeout(() => {
            alert(`注册成功: ${JSON.stringify(formData)}`);
        }, 100)

    }

}



bindEvent();